package lee.filter;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Autor zhangjiawen
 * @Date: 2020/5/29 9:07
 */
@Slf4j
public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";//表示请求之前拦截
    }

    @Override
    public int filterOrder() {
        return -1;
    }

    @Override
    public boolean shouldFilter() {
        return true;//如果想要过滤器生效必须改成true
    }

    /**
     * 转发解析token
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //1获取当前用户身份信息
        RequestContext ctx=RequestContext.getCurrentContext();
            //从上下文拿到身份对象
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        if(!(authentication instanceof OAuth2Authentication)){
            log.error("-----!(authentication instanceof OAuth2Authentication)");
            return null;//如果不是oauth2.0格式的对象 直接返回；
        }
        OAuth2Authentication oAuth2Authentication=(OAuth2Authentication) authentication;
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
        //取出用户身份
        String principal = userAuthentication.getName();
        //2获取当前用户权限信息
        List<String> authorities=new ArrayList<>();
            //采用stream流的方式遍历
        userAuthentication.getAuthorities().stream().forEach(c-> authorities.add(c.getAuthority()));
            //将原请求参数重新放回
        OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request();
        Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
        Map<String, Object> jsonToken =new HashMap<>(requestParameters);
        //3把用户身份权限信息放入json，存入http的header中
        if(userAuthentication!=null){
            jsonToken.put("principal",principal);
            jsonToken.put("authorities",authorities);
        }

        ctx.addZuulRequestHeader("json-token", Base64.encode(JSON.toJSONString(jsonToken)));
        //4转发给微服务



        return null;
    }
}
